using GameConfig;
using System.Collections;
using System.Collections.Generic;
using TEngine;
using UnityEngine;
using GameLogic;
using System;

/// <summary>
/// 种子类，里面应该包含土地的信息，种子的基本信息即配置表信息和种子的实时数据信息，即退出需要保存的信息
/// </summary>
public class Crop : MonoBehaviour
{
    public TbSeedBase seedBaseMsg;  //种子的基本信息
    public TileDetails tileDetails; //土地的实时信息
    public SeedDetails seedDetails;  //种子的实时数据信息
    public TbSeedBaseAttribute seedBaseAttribute; //种子的基础属性
    private int harvestActionCount;
    private bool isVisible = false;
    private Animator anim;

    public void SetVisibility(bool visible)
    {
        isVisible = visible;
    }

    public void InitCrop(int seedID, TileDetails tileDetails, TbSeedBase seed)
    {
        this.tileDetails = tileDetails;
        this.seedBaseMsg = seed;
        seedBaseAttribute = ConfigSystem.Instance.Tables.SeedBaseAttribute.Get(seedID);
        this.seedDetails = new SeedDetails();
        InitSeedDetails(seedDetails,seedID);
        this.tileDetails.PlantedSeed = seedDetails;
        GameEvent.AddEventListener(ILoginUI_Event.OnTimerChange, UpdateCropStatus);
    }

    public void InitSeedDetails(SeedDetails seedDetails,int seedID)
    {
        seedDetails.SeedID = seedID;
        seedDetails.currentGrowthTime = 0;
        seedDetails.DeathTimer = 0f;
        seedDetails.currentGrowthStages = 0;
        seedDetails.currentDayTime = 0;
        seedDetails.currentCropPrefab = seedBaseMsg.GrowthPrefabs[seedDetails.currentGrowthStages];
        seedDetails.BaseSeedDropRate = float.Parse(ConfigSystem.Instance.Tables.SeedBaseAttribute.Get(seedID).BaseSeedDropRate);
    }



    public float CalculateHappiness(SeedDetails seed, TileDetails tile)
    {
        // 如果作物已经死亡，开心度为0
        if (seed.IsCropDead)
            return 0f;

        // 计算温度适宜度
        float tempSuitability = CalculateParameterSuitability(
            tile.Temperature,
            seedBaseAttribute.OptimalTempMin, seedBaseAttribute.OptimalTempMax,
            seedBaseAttribute.ExtremeTempMin, seedBaseAttribute.ExtremeTempMax);

        // 计算湿度适宜度
        float moistureSuitability = CalculateParameterSuitability(
            tile.Wetness,
            seedBaseAttribute.OptimalMoistureMin, seedBaseAttribute.OptimalMoistureMax,
            seedBaseAttribute.ExtremeMoistureMin, seedBaseAttribute.ExtremeMoistureMax);

        // 计算肥度适宜度
        float fertilitySuitability = CalculateParameterSuitability(
            tile.Fertility,
            seedBaseAttribute.OptimalFertilityMin, seedBaseAttribute.OptimalFertilityMax,
            seedBaseAttribute.ExtremeFertilityMin, seedBaseAttribute.ExtremeFertilityMax);

        // 综合开心度（取三个适宜度的平均值）
        float happiness = (tempSuitability + moistureSuitability + fertilitySuitability) / 3f;

        return Math.Clamp(happiness, 0f, 1f);
    }

    // 计算单个参数的适宜度
    private float CalculateParameterSuitability(float value, float optimalMin, float optimalMax,
                                                     float extremeMin, float extremeMax)
    {
        // 如果值超出极限范围，适宜度为0
        if (value < extremeMin || value > extremeMax)
            return 0f;

        // 如果值在最适范围内，适宜度为1
        if (value >= optimalMin && value <= optimalMax)
            return 1f;

        // 如果在极限范围内但不在最适范围内，计算线性衰减
        if (value < optimalMin)
        {
            // 计算从极限最小值到最适最小值的衰减
            return (value - extremeMin) / (optimalMin - extremeMin);
        }
        else // value > optimalMax
        {
            // 计算从最适最大值到极限最大值的衰减
            return (extremeMax - value) / (extremeMax - optimalMax);
        }
    }

    // 更新作物状态（每天调用）
    public void UpdateCropStatus()
    {

        if (tileDetails.PlantedSeed == null || tileDetails.PlantedSeed.IsCropDead || tileDetails.PlantedSeed.IsRipe)
            return;

        var seedDetails = tileDetails.PlantedSeed;

        // 检查是否超出极限条件
        bool isBeyondExtreme =
            tileDetails.Temperature < seedBaseAttribute.ExtremeTempMin || tileDetails.Temperature > seedBaseAttribute.ExtremeTempMax ||
            tileDetails.Wetness < seedBaseAttribute.ExtremeMoistureMin || tileDetails.Wetness > seedBaseAttribute.ExtremeMoistureMax ||
            tileDetails.Fertility < seedBaseAttribute.ExtremeFertilityMin || tileDetails.Fertility > seedBaseAttribute.ExtremeFertilityMax;

        if (isBeyondExtreme)
        {
            // 增加死亡计时器
            seedDetails.DeathTimer ++;

            // 如果超出极限条件时间超过阈值，作物死亡
            if (seedDetails.DeathTimer >= float.Parse(seedBaseAttribute.DeathTimeThreshold))
            {
                seedDetails.IsCropDead = true;
            }
        }
        else
        {
            // 重置死亡计时器
            if (seedDetails.DeathTimer != 0)
            {
                seedDetails.DeathTimer = 0f;
            }
            //成长阶段
            seedDetails.currentGrowthTime++;
            int growthStages = seedBaseMsg.GrowthTime.Count;
            int currentStage = 0;
            int accumulatedTime = 0;
            // 正序计算当前阶段
            for (int i = 0; i < growthStages; i++)
            {
                accumulatedTime += seedBaseMsg.GrowthTime[i];

                if (seedDetails.currentGrowthTime <= accumulatedTime)
                {
                    currentStage = i;
                    break;
                }

                // 如果已经超过所有阶段，保持在最后阶段
                if (i == growthStages - 1)
                {
                    tileDetails.PlantedSeed.IsRipe = true;
                    currentStage = i;
                }
            }
            if (currentStage != seedDetails.currentGrowthStages)
            {
                seedDetails.currentGrowthStages= currentStage;
                //获取当前阶段的Prefab
                string cropPrefab = seedBaseMsg.GrowthPrefabs[currentStage];

                if (CropManager.Instance.cropParent == null)
                {
                    GameObject emptyGo = new GameObject("cropParent");
                    emptyGo.transform.position = Vector3.zero;
                    emptyGo.AddComponent<DontDestory>();
                    CropManager.Instance.cropParent = emptyGo.transform;
                }
                if(cropPrefab!= seedDetails.currentCropPrefab)  //需要换模型了好像是
                {
                    seedDetails.currentCropPrefab= cropPrefab;
                }
                Sprite cropSprite = GameModule.Resource.LoadAsset<Sprite>( seedBaseMsg.GrowthSprites[currentStage]);
                this.GetComponentInChildren<SpriteRenderer>().sprite = cropSprite;
            }
        }
        Debug.Log(string.Format("当前种子的ID是{0},满意度是{1}",seedDetails.Name, CalculateHappiness(seedDetails, tileDetails)));
    }

    // 收获作物
    public HarvestResult HarvestCrop(TileDetails tile)
    {
        if (tile.PlantedSeed == null)
            return new HarvestResult { Yield = 0, SeedDropChance = 0 };

        var seed = tile.PlantedSeed;
        float happiness = CalculateHappiness(seed, tile);

        // 计算实际产量（基于基础产量和开心度）
        int actualYield = (int)(Convert.ToInt32(seedBaseAttribute.BaseYield) * (1 + happiness));

        // 计算种子掉落概率（基于基础概率和开心度）
        float seedDropChance = seed.BaseSeedDropRate * (1 + happiness);

        // 重置土地状态
        tile.PlantedSeed = null;
        seedDetails.IsCropDead = false;
        tile.seedItemID = -1;
        tile.alreadySown = false;

        return new HarvestResult
        {
            Yield = actualYield,
            SeedDropChance = seedDropChance
        };
    }

    public void ProcessToolAction(ItemDetails tool, TileDetails tile)
    {
        tileDetails = tile;

        //工具使用次数
        int requireActionCount = 5;// cropDetails.GetTotalRequireCount(tool.itemID);
        if (requireActionCount == -1) return;

        anim = GetComponentInChildren<Animator>();

        //点击计数器
        if (harvestActionCount < requireActionCount)
        {
            harvestActionCount++;

            //判断是否有动画 树木
            //if (anim != null && cropDetails.hasAnimation)
            //{
            //    if (PlayerTransform.position.x < transform.position.x)
            //        anim.SetTrigger("RotateRight");
            //    else
            //        anim.SetTrigger("RotateLeft");
            //}
            ////播放粒子
            //if (cropDetails.hasParticalEffect)
            //    EventHandler.CallParticleEffectEvent(cropDetails.effectType, transform.position + cropDetails.effectPos);
            ////播放声音
            //if (cropDetails.soundEffect != SoundName.none)
            //{
            //    EventHandler.CallPlaySoundEvent(cropDetails.soundEffect);
            //}
        }

        if (harvestActionCount >= requireActionCount)
        {
            //if (cropDetails.generateAtPlayerPosition || !cropDetails.hasAnimation)
            //{
            //    //生成农作物
            //    SpawnHarvestItems();
            //}
            //else if (cropDetails.hasAnimation)
            //{
            //    if (PlayerTransform.position.x < transform.position.x)
            //        anim.SetTrigger("FallingRight");
            //    else
            //        anim.SetTrigger("FallingLeft");
            //    EventHandler.CallPlaySoundEvent(SoundName.TreeFalling);
            //    StartCoroutine(HarvestAfterAnimation());
            //}
        }
    }

    private IEnumerator HarvestAfterAnimation()
    {
        while (!anim.GetCurrentAnimatorStateInfo(0).IsName("END"))
        {
            yield return null;
        }

        SpawnHarvestItems();
        //转换新物体
        //if (cropDetails.transferItemID > 0)
        //{
        //    CreateTransferCrop();
        //}
    }

    private void CreateTransferCrop()
    {
        //tileDetails.seedItemID = cropDetails.transferItemID;
        //tileDetails.daysSinceLastHarvest = -1;
        //tileDetails.growthDays = 0;

        //EventHandler.CallRefreshCurrentMap();
    }

    /// <summary>
    /// 生成果实
    /// </summary>
    public void SpawnHarvestItems()
    {
        //for (int i = 0; i < cropDetails.producedItemID.Length; i++)
        //{
        //    int amountToProduce;

        //    if (cropDetails.producedMinAmount[i] == cropDetails.producedMaxAmount[i])
        //    {
        //        //代表只生成指定数量的
        //        amountToProduce = cropDetails.producedMinAmount[i];
        //    }
        //    else    //物品随机数量
        //    {
        //        amountToProduce = Random.Range(cropDetails.producedMinAmount[i], cropDetails.producedMaxAmount[i] + 1);
        //    }

        //    //执行生成指定数量的物品
        //    for (int j = 0; j < amountToProduce; j++)
        //    {
        //        if (cropDetails.generateAtPlayerPosition)
        //        {
        //            EventHandler.CallHarvestAtPlayerPosition(cropDetails.producedItemID[i]);
        //        }
        //        else    //世界地图上生成物品
        //        {
        //            //判断应该生成的物品方向
        //            var dirX = transform.position.x > PlayerTransform.position.x ? 1 : -1;
        //            //一定范围内的随机
        //            var spawnPos = new Vector3(transform.position.x + Random.Range(dirX, cropDetails.spawnRadius.x * dirX),
        //            transform.position.y + Random.Range(-cropDetails.spawnRadius.y, cropDetails.spawnRadius.y), 0);

        //            EventHandler.CallInstantiateItemInScene(cropDetails.producedItemID[i], spawnPos);
        //        }
        //    }
        //}

        //if (tileDetails != null)
        //{
        //    tileDetails.daysSinceLastHarvest++;

        //    //是否可以重复生长
        //    if (cropDetails.daysToRegrow > 0 && tileDetails.daysSinceLastHarvest < cropDetails.regrowTimes - 1)
        //    {
        //        tileDetails.growthDays = cropDetails.TotalGrowthDays - cropDetails.daysToRegrow;
        //        //刷新种子
        //        EventHandler.CallRefreshCurrentMap();
        //    }
        //    else    //不可重复生长
        //    {
        //        tileDetails.daysSinceLastHarvest = -1;
        //        tileDetails.seedItemID = -1;
        //        //FIXME:自己设计
        //        // tileDetails.daysSinceDug = -1;

        //    }
        //    Destroy(gameObject);

        //}

    }
}

// 收获结果
public struct HarvestResult
{
    public int Yield; // 收获的果实数量
    public float SeedDropChance; // 掉落种子的概率
}
